import dva from 'dva'
import createLoading from 'dva-loading'
import './index.css'
import { Toast } from 'antd-mobile'
import authorityList from './common/authority'
import createHistory from 'history/createBrowserHistory'
import {routerRedux} from 'dva/router'

// 1. Initialize
const app = dva({
  history: createHistory({
    basename: '/'
  }),
  onError(error, dispatch) {
    setTimeout(() => {
      if (error.errCode === 401) {
        localStorage.clear()
        dispatch(routerRedux.push('/login'))
      }

      Toast.info(`${error.errCode}错误： ${error.errMsg}`)
    },1001)
  },
  onStateChange(state){
    const { loading, account } = state

    if (account.me && account.me.role && account.me.role.name) {
      const role = account.me.role.name
      if (!authorityList.includes(role)){
        Toast.info('该账号没有权限登录', 2)
        return
      }
    }

    if (loading.global) {
      Toast.loading('加载中...', 1)
    }else{
      Toast.hide()
    }
  }
})

// 2. Plugins
app.use(createLoading())

// 3. Model
app.model(require('./models/Global').default)

// 4. Router
app.router(require('./router').default)

// 5. Start
app.start('#root')
